package com.annotationAndReflection;

import com.cmy.packaging.Test;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

//通过反射获取泛型
public class TestGeneric {
    public void test01(Map<String,User> map, List<User> list){
        System.out.println("test01");
    }
    public Map<String,User> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        //类名.class获取Class对象
        Method method = TestGeneric.class.getMethod("test01", Map.class, List.class);
        //获取泛型信息
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#1:"+genericParameterType);
            //java.util.Map<java.lang.String, com.annotationAndReflection.User>
            //java.util.List<com.annotationAndReflection.User>
            //取出具体的,判断该参数类型是否是结构化参数类型
            if (genericParameterType instanceof ParameterizedType){
                //强转为参数化类型,调用获得真实类型信息方法获取真实泛型参数信息
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                    //class java.lang.String
                    //class com.annotationAndReflection.User
                    //class com.annotationAndReflection.User
                }
            }
        }

        Method method2 = TestGeneric.class.getMethod("test02", null);
        Type genericReturnType = method2.getGenericReturnType();//该方法具有返回值,通过getReturnType方法获得返回值类型
        //如果该返回值类型属于结构化参数类型,泛型就将其打印
        if (genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
                //class java.lang.String
                //class com.annotationAndReflection.User
            }
        }


    }
}

    